package com.csc.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.csc.bean.NewMember;
import com.csc.bean.SystemAccountBean;
import com.csc.domain.SystemAccount;
import com.csc.domain.SystemAccountType;
import com.csc.domain.SystemStatus;
import com.csc.domain.TransactionHistory;
import com.csc.service.SystemAccountService;
import com.csc.service.SystemAccountTypeService;
import com.csc.service.SystemStatusService;
import com.csc.service.SystemTransactionHistoryService;
import com.csc.service.ValidatorService;

import constants.Constant;

@Controller
@SessionAttributes("user")
public class SystemAccountController {
	@Autowired
	private SystemAccountService sysAccSer;
	@Autowired
	ValidatorService validService;

	@Autowired
	SystemStatusService SYSTEM_STATUS_SERVIVE;
	@Autowired
	SystemAccountTypeService SYS_ACC_TYPE_SERVICE;
	static Logger logger = Logger.getLogger(LoginController.class);
	// SystemAccountServiceImp sysAccSer = new SystemAccountServiceImp();

	@Autowired
	SystemTransactionHistoryService transactionHistoryService;

	@RequestMapping(value = "/home")
	public String getAccountList(HttpServletRequest request, Model model) {
		List<SystemAccount> accountList = sysAccSer.getAccounts();
		List<SystemAccountType> accTypeList = sysAccSer.getAccountsType();
		String message = "";
		if (request.getParameter("mess") == null) {
			message = "";
		} else {
			message = request.getParameter("mess");
			System.out.println(" " + message);
		}
		model.addAttribute("listAccount", accountList);
		model.addAttribute("listAccountType", accTypeList);
		model.addAttribute("message", message);
		return ("home");
	}

	// Nguyen Vu Hung - Change password
	@RequestMapping(value = "/adminChangePassword", method = RequestMethod.POST)
	public String doAdminChangePassword(
			@RequestParam(value = "oldPassword") String oldPass,
			@RequestParam(value = "newPassword") String newPass,
			@RequestParam(value = "confirmNewPassword") String coNewPass,
			@ModelAttribute("user") String username, Model model) {
		String message = validService.checkUpdatePassword(username, oldPass,
				newPass, coNewPass);

		if (null == message) {
			sysAccSer.updatePassword(username,
					validService.encodePassword(newPass));
		} else {
			model.addAttribute("message", message);
		}

		return "forward:/settingAdmin.html";
	}

	@RequestMapping(value = "/adminChangeFullName")
	public String doAdminChangeFullName(
			@RequestParam(value = "txtFirstName") String fName,
			@RequestParam(value = "txtMidName") String mName,
			@RequestParam(value = "txtLastName") String lName,
			@ModelAttribute("user") String username, Model model) {

		String message = validService.checkFullName(fName, lName, mName);
		if (message.equals("")) {
			sysAccSer.updateAdminName(username, fName, lName, mName);
		} else {
			model.addAttribute("message", message);

		}
		return "forward:/settingAdmin.html";
	}

	@RequestMapping(value = "/adminChangeIdCardNumber")
	public String doAdminChangeIdCardNumber(
			@RequestParam(value = "txtIdCardNumber") String idCardNo,
			@ModelAttribute("user") String username, Model model) {
		

		String message = validService.checkIDCardNumber(idCardNo);

		if (message.equals("")) {
			sysAccSer.updateAdminIdCardNumber(username, idCardNo);
		} else {
			model.addAttribute("message", message);

		}

		return "forward:/settingAdmin.html";
	}

	@RequestMapping(value = "/adminChangePhone")
	public String doAdminChangePhone(
			@RequestParam(value = "txtPhone1") String phone1,
			@RequestParam(value = "txtPhone2") String phone2,
			@ModelAttribute("user") String username, Model model) {

		String message = validService.checkPhoneNumber(phone1, phone2);

		if (message.equals("")) {
			sysAccSer.updateAdminPhone(username, phone1, phone2);
		} else {
			model.addAttribute("message", message);

		}

		return "forward:/settingAdmin.html";
	}

	@RequestMapping(value = "/adminChangeAddress")
	public String doAdminChangeAddress(
			@RequestParam(value = "txtAddress1") String address1,
			@RequestParam(value = "txtAddress2") String address2,
			@ModelAttribute("user") String username, Model model) {

		String message = validService.checkAddress(address1, address2);

		
		if (message.equals("")) {
			sysAccSer.updateAdminAddress(username, address1, address2);
		} else {
			model.addAttribute("message", message);

		}
		return "forward:/settingAdmin.html";
	}

	@RequestMapping(value = "/adminChangeEmail")
	public String doAdminChangeEmail(
			@RequestParam(value = "txtEmail1") String email1,
			@RequestParam(value = "txtEmail2") String email2,
			@ModelAttribute("user") String username, Model model) {
		String message = validService.checkEmail(email1, email2);
		
		if (message.equals("")) {
			sysAccSer.updateAdminEmail(username, email1, email2);
		} else {
			model.addAttribute("message", message);

		}

		return "forward:/settingAdmin.html";
	}

	/* @author: Tran Son Hoang--- action: Search New User Registration */
	@RequestMapping(value = "/SearchNewUserRegistrationByAdvanced", method = RequestMethod.POST)
	public String doSearchNewUserRegistrationByAdvanced(
			@RequestParam("SearchByName") String name,
			@RequestParam("LoginId") String LoginId,
			@RequestParam("IdCardNumber") String IdCardNumber,
			@RequestParam("phone") String phone,
			@RequestParam("address") String address,
			@RequestParam("email") String email,
			@RequestParam("role") String role, Model model) {
		logger.info("Admin is searching...");
		List<TransactionHistory> ResultSearch = sysAccSer
				.searchNewUserRegistrationByAdvanced(name, LoginId,
						IdCardNumber, phone, address, email, role);
		model.addAttribute("viewNewUsers", ResultSearch);
		return "admin/newUser";
	}


	/* @author: Tran Son Hoang--- action: Search Name New User Registration */
	@RequestMapping(value = "/SearchNewUserRegistrationByAdvanced/{name}/{LoginId}/{IdCardNumber}/{phone}/{email/{address}/{role}", method = RequestMethod.GET)
	public @ResponseBody List<NewMember> searchAdvancedAdminNewUser(
			@PathVariable("name") String name,
			@PathVariable("LoginId") String LoginId,
			@PathVariable("IdCardNumber") String IdCardNumber,
			@PathVariable("phone") String phone,
			@PathVariable("email") String email,
			@PathVariable("address") String address,
			@PathVariable("role") String role) {
		
		List<TransactionHistory> listAll = sysAccSer.searchNewUserRegistrationByAdvanced(name, LoginId, IdCardNumber, phone, address, email, role);
		return sysAccSer.parseToNewUsers(listAll);
	}

	/* @author:Tran Son Hoang --- action: Approve and reject new user */
	@RequestMapping(value = "/ApproveOrRejectNewUser", method = RequestMethod.POST)
	public String doApproveOrRejectNewUser(
			@RequestParam("action") String action,
			@RequestParam("checkBox") String[] listCheck,
			@ModelAttribute("user") String AccImpact, Model model) {
		String ApproveAndRejectMessage = "";
		if (!action.equals("")) {
			if (action.equals(Constant.ACTION_APPROVE_NEWUSER)) {
				logger.info("admin" + action + " new user...");
				// create loop for each checkbox
				for (int i = 0; i < listCheck.length; i++) {
					Date date = new Date();
					SimpleDateFormat dateFormat = new SimpleDateFormat(
							Constant.SIMPLE_DATE_FORMAT);
					String timeAction = dateFormat.format(date);
					SystemAccount AccImp = sysAccSer
							.getAccountByUsername(AccImpact);
					SystemAccount AccEffect = sysAccSer
							.getAccountByUsername(listCheck[i]);
					SystemStatus sysStt = SYSTEM_STATUS_SERVIVE
							.getStatusByID(Constant.STATUS_ID_COMPLETE);
					TransactionHistory transactionHistory = new TransactionHistory(
							timeAction, Constant.ACTION_ACTIVE_USER,
							Constant.ACTION_ACTIVE_USER);
					transactionHistory.setAccImpact(AccImp);
					transactionHistory.setAccAffected(AccEffect);
					transactionHistory.setSystemStatus(sysStt);
					sysAccSer.RejectNewUserInAdminPage(transactionHistory,
							listCheck[i], Constant.STATUS_ID_PREACTIVE);
				}
				ApproveAndRejectMessage = "Approving Successful!";
				model.addAttribute("ApproveAndRejectMessage",
						ApproveAndRejectMessage);
				return "forward:/loadNewmember.html";
			} else {
				logger.info("admin" + action + " new user...");
				for (int i = 0; i < listCheck.length; i++) {
					Date date = new Date();
					SimpleDateFormat dateFormat = new SimpleDateFormat(
							Constant.SIMPLE_DATE_FORMAT);
					String timeAction = dateFormat.format(date);
					SystemAccount AccImp = sysAccSer
							.getAccountByUsername(AccImpact);
					SystemAccount AccEffect = sysAccSer
							.getAccountByUsername(listCheck[i]);
					SystemStatus sysStt = SYSTEM_STATUS_SERVIVE
							.getStatusByID(Constant.STATUS_ID_COMPLETE);
					TransactionHistory transactionHistory = new TransactionHistory(
							timeAction, Constant.ACTION_REJECT_NEWUSER,
							Constant.ACTION_REJECT_NEWUSER);
					transactionHistory.setAccImpact(AccImp);
					transactionHistory.setAccAffected(AccEffect);
					transactionHistory.setSystemStatus(sysStt);
					sysAccSer.RejectNewUserInAdminPage(transactionHistory,
							listCheck[i], Constant.STATUS_ID_REJECTS);
				}
				
				ApproveAndRejectMessage = "Rejecting Successful!";
				model.addAttribute("ApproveAndRejectMessage",
						ApproveAndRejectMessage);
				return "forward:/loadNewmember.html";
			}
			/*List<TransactionHistory> viewNewUsers = sysAccSer
					.getListAdminNewUsers();
			model.addAttribute("viewNewUsers", viewNewUsers);*/
		} else {
			ApproveAndRejectMessage = Constant.APPROVE_FAIL;
			model.addAttribute("ApproveAndRejectMessage",
					ApproveAndRejectMessage);
		}
		return "forward:/loadNewmember.html";
	}

	/*
	 * @author:Tran Son Hoang: action---create new account...
	 * LoginId,IdCardNumber,firstName,middleName,lastName,
	 * phone1,phone2,address1,address2,email1,email2,role.
	 */
	
	@RequestMapping(value = "/createNewAccountzz", method = RequestMethod.POST)
	public String doCreateNewAccount(@RequestParam("LoginId") String LoginId,
			@RequestParam("IdCardNumber") String IdCardNumber,
			@RequestParam("firstName") String firstName,
			@RequestParam("middleName") String middleName,
			@RequestParam("lastName") String lastName,
			@RequestParam("phone1") String phone1,
			@RequestParam("phone2") String phone2,
			@RequestParam("address1") String address1,
			@RequestParam("address2") String address2,
			@RequestParam("email1") String email1,
			@RequestParam("email2") String email2,
			@RequestParam("role") String role, Model model,
			@ModelAttribute("user") String accImpact) {

		boolean check = true;
		SystemAccountBean acc = new SystemAccountBean();
		acc.setAccountLoginId(LoginId);
		acc.setAccountIDCardNumber(IdCardNumber);
		acc.setAccountFirstName(firstName);
		acc.setAccountMidName(middleName);
		acc.setAccountLastName(lastName);
		acc.setAccountPhone1(phone1);
		acc.setAccountPhone2(phone2);
		acc.setAccountAddress1(address1);
		acc.setAccountAddress2(address2);
		acc.setAccountEmail1(email1);
		acc.setAccountEmail2(email2);
		acc.setRole(role);
		String[] message = validService.checkCreateAccount(acc);
		logger.info("result : "+message[0]);
		if(!message[0].equals("")){
			model.addAttribute("validate", message[0]);
			check = false;
		}
		
		if (check) {
			logger.info("Test");
			SystemStatus newAccStt = SYSTEM_STATUS_SERVIVE
					.getStatusByID(Constant.STATUS_ID_NEW);
			int AccRole = Integer.parseInt(role);
			SystemAccountType AccountRole = SYS_ACC_TYPE_SERVICE
					.getTypeByID(AccRole);
			logger.info("Test1");
			if (sysAccSer.createNewSystemAccount(LoginId, IdCardNumber,
					firstName, lastName, middleName, phone1, phone2, email1,
					email2, address1, address2, AccountRole, newAccStt)) {
				logger.info("Test2");
				SystemAccount accAffec = sysAccSer
						.getAccountByUsername(LoginId);

				Date date = new Date();
				SimpleDateFormat dateFormat = new SimpleDateFormat(
						Constant.SIMPLE_DATE_FORMAT);

				String timeAction = dateFormat.format(date);
				SystemAccount accIm = sysAccSer.getAccountByUsername(accImpact);

				SystemStatus sysStt = SYSTEM_STATUS_SERVIVE
						.getStatusByID(constants.Constant.STATUS_ID_NEW);
				TransactionHistory trans = new TransactionHistory(timeAction,
						Constant.ACTION_CREATE_NEWUSER,
						Constant.ACTION_CREATE_NEWUSER);
				trans.setAccImpact(accIm);
				trans.setAccAffected(accAffec);
				trans.setSystemStatus(sysStt);
				System.out.println(" " + accAffec.getAccountLoginId() + " "
						+ accIm.getAccountLoginId());

				if (sysAccSer.createNewTransactionHistory(trans)) {
					String success="Create new account successful!";
					model.addAttribute("Success", success);
				}

			} else {
				return "forward:/loadNewmember.html";
			}

			return "forward:/loadNewmember.html";
		} else {
			SystemAccount sysAcc = sysAccSer.getAccountByLoginId(accImpact);
			model.addAttribute("role", sysAcc.getSystemAccountType().getTypeId());
			return "admin/register";
		}
	}

	/* @author:Tran Son Hoang---Action:User/settings */
	@RequestMapping(value = "/userChangePassword", method = RequestMethod.POST)
	public String doUserChangePassword(
			@RequestParam(value = "CurrentPassword") String oldPass,
			@RequestParam(value = "newpassword") String newPass,
			@RequestParam(value = "confirmNewPassword") String cofirmNewPass,
			@ModelAttribute("user") String username, Model model) {
		logger.info("old pass:" + oldPass + " new pass: " + newPass
				+ " confirm: " + cofirmNewPass);
		
		String check = validService.checkUpdatePassword(username, oldPass, newPass, cofirmNewPass);
		if(!check.equals("")){
			model.addAttribute("UpdateMessage", check);
			return "forward:/userSettings.html";
		}else{
		if (sysAccSer.updatePassword(username, newPass)) {
			String message = "update sucessfull!";
			logger.info("updating successful password of user "+username);
			model.addAttribute("UpdateMessage", message);
			
			Date date = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat(
					Constant.SIMPLE_DATE_FORMAT);

			String timeAction = dateFormat.format(date);
			SystemAccount accIm = sysAccSer.getAccountByUsername(username);
			SystemStatus sysStt = SYSTEM_STATUS_SERVIVE
					.getStatusByID(constants.Constant.STATUS_ID_COMPLETE);
			TransactionHistory trans = new TransactionHistory(timeAction,
					Constant.ACTION_UPDATE_PASSWORD,
					Constant.ACTION_UPDATE_PASSWORD);
			trans.setAccImpact(accIm);
			trans.setSystemStatus(sysStt);
			// Acc imp and acc affect is the same
			trans.setAccAffected(accIm);
			if (sysAccSer.createNewTransactionHistory(trans)) {
				logger.info("save new password into database successful");
			}
			return "forward:/userSettings.html";
		}else{
			logger.info("updating failure password of user "+username);
			String message = "System cannot update now!";
			model.addAttribute("UpdateMessage", message);
			return "forward:/userSettings.html";
		}
		}
		
		
	}

	// end User/settings
	
	@RequestMapping(value = "/loadDetailNewUser", method = RequestMethod.POST)
	public @ResponseBody SystemAccountBean add(@RequestParam("loginid") String loginid,HttpServletRequest request, HttpServletResponse response){
		SystemAccount result = sysAccSer.getNewUserDetail(loginid);
		SystemAccountBean acc = new SystemAccountBean();
		String accountLoginId = result.getAccountLoginId();
		String accountIDCardNumber = result.getAccountIDCardNumber();
		String accountFirstName = result.getAccountFirstName();
		String accountMidName = result.getAccountMidName();
		String accountLastName = result.getAccountLastName();
		String accountPhone1 = result.getAccountPhone1();
		String accountPhone2 = result.getAccountPhone2();
		String accountEmail1 = result.getAccountEmail1();
		String accountEmail2 = result.getAccountEmail2();
		String accountAddress1 = result.getAccountAddress1();
		String accountAddress2 = result.getAccountAddress2();
		
		acc.setAccountLoginId(accountLoginId);
		acc.setAccountIDCardNumber(accountIDCardNumber);
		acc.setAccountFirstName(accountFirstName);
		acc.setAccountMidName(accountMidName);
		acc.setAccountLastName(accountLastName);
		acc.setAccountPhone1(accountPhone1);
		acc.setAccountPhone2(accountPhone2);
		acc.setAccountEmail1(accountEmail1);
		acc.setAccountEmail2(accountEmail2);
		acc.setAccountAddress1(accountAddress1);
		acc.setAccountAddress2(accountAddress2);
		return acc;
	}
	/*public String doLoadDetailNewUser(@RequestParam("loginId") String loginid,Model model){
		if(!loginid.equals("")){
			logger.info("load detail " + loginid);
			SystemAccount result = sysAccSer.getNewUserDetail(loginid);
			
			model.addAttribute("DetailResult", result);
		}
		logger.info("load detail null");
		return "forward:/newmember.html";
	
	}*/
	
}
